package com.ejiaoyi.api.service.impl;

import com.alibaba.fastjson.JSON;

import com.ejiaoyi.api.common.HTTPSCertifiedClient;
import com.ejiaoyi.api.common.HTTPSClientUtil;
import com.ejiaoyi.api.enums.ResultInfoEnum;
import com.ejiaoyi.api.model.block.ResBlockModel;
import com.ejiaoyi.api.model.chaincode.ResModel;
import com.ejiaoyi.api.service.CommonService;
import com.ejiaoyi.api.util.SignUtil;
import com.ejiaoyi.api.util.exception.GlobalException;
import org.apache.http.client.HttpClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.Map;


@Service
public class CommonServiceImpl implements CommonService {

    @Value("${nodeUrl}")
    private String nodeUrl;

    @Value("${blockUrl}")
    private String blockUrl;

    @Value("${http_cert_path}")
    private String httpCertPath;

    @Value("${gateway_public_cert_path}")
    private String gatewayPublicCertPath;


    @Override
    public ResModel req(Map<String, Object> paramMap, String encryptionValue) {
        String res = "";
        try {

            HttpClient httpClient = getHttpClient();

            String param = JSON.toJSONString(paramMap);

            res = HTTPSClientUtil.doPost(httpClient, nodeUrl, param);

            System.out.println("响应结果：" + res);
        } catch (Exception e) {
            e.printStackTrace();
            throw new GlobalException(ResultInfoEnum.SYSTEM_ERROR);
        }
        if (res != null && res.length() > 0) {

            ResModel resModel = JSON.parseObject(res, ResModel.class);

            // 验签、数据转换

            if (resModel == null) {
                throw new GlobalException("响应结果无效");
            }

            boolean result = false;
            try {
                result = SignUtil.verifyByCertPath(getGatewayPublicCertPath(), resModel.getMac(), encryptionValue);
            } catch (Exception e) {
                throw new GlobalException(ResultInfoEnum.RES_MAC_ERROR);
            }
            if (!result) {
                throw new GlobalException("验签失败");
            }

            if (resModel.getHeader().getCode() != 0) {
                throw new GlobalException(resModel.getHeader().getMsg());
            }

            return resModel;

        } else {
            throw new GlobalException(ResultInfoEnum.SYSTEM_ERROR);
        }
    }


    private HttpClient getHttpClient() throws Exception {
        Resource keystoreResource = new ClassPathResource(httpCertPath);
        File keystoreFile = keystoreResource.getFile();
        return new HTTPSCertifiedClient().init(keystoreFile.getAbsolutePath());
    }


    private String getGatewayPublicCertPath() throws Exception {
        Resource keystoreResource = new ClassPathResource(gatewayPublicCertPath);
        File keystoreFile = keystoreResource.getFile();
        return keystoreFile.getAbsolutePath();
    }


    @Override
    public ResBlockModel reqBlock(Map<String, Object> paramMap, String encryptionValue) {
        String res = "";
        try {
            HttpClient httpClient = getHttpClient();

            res = HTTPSClientUtil.doPost(httpClient, blockUrl, JSON.toJSONString(paramMap));

        } catch (Exception e) {
            throw new GlobalException(ResultInfoEnum.SYSTEM_ERROR);
        }
        if (res != null && res.length() > 0) {
            ResBlockModel resModel = JSON.parseObject(res, ResBlockModel.class);
            // 验签、数据转换
            if (resModel == null) {
                throw new GlobalException("响应结果无效");
            }

            boolean result = false;
            try {
                result = SignUtil.verifyByCertPath(getGatewayPublicCertPath(), resModel.getMac(), encryptionValue);
            } catch (Exception e) {
                throw new GlobalException(ResultInfoEnum.RES_MAC_ERROR);
            }
            if (!result) {
                throw new GlobalException("验签失败");
            }

            if (resModel.getHeader().getCode() != 0) {
                throw new GlobalException(resModel.getHeader().getMsg());
            }

            return resModel;

        } else {
            throw new GlobalException(ResultInfoEnum.SYSTEM_ERROR);
        }
    }
}
